package com.example.test.applicaiton.services.imp;

import com.example.test.applicaiton.services.ArticleCategoryService;
import com.example.test.domain.mapper.ArticleCategoryMapper;
import com.example.test.domain.entity.ArticleCategory;
import com.example.test.applicaiton.vo.ArticleCategoryVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Log4j2
public class ArticleCategoryServiceImpl implements ArticleCategoryService {
    @Resource
    private ArticleCategoryMapper articleCategoryMapper;

    @Override
    public ArticleCategoryVO findOne(int categoryId) {
        return articleCategoryMapper.findOneById(categoryId);
    }

    @Override
    public List<ArticleCategory> findAll() {
//        log
        List<ArticleCategory> cateList = articleCategoryMapper.findAll();
        List<ArticleCategory> result = new ArrayList<>();
        for (ArticleCategory category : cateList) {
            if (category.isParentCategory()) {
                result.add(category);
            }
        }
        //获取一级分类下的所有子分类
        for (ArticleCategory category : result) {
            List<ArticleCategory> childData = _getChild(category.getId(), cateList);
            category.setSubCategory(childData);
        }
        return result;
    }

    private List<ArticleCategory> _getChild(int parentId, List<ArticleCategory> articleList) {
        List<ArticleCategory> childList = new ArrayList<>();
        for (ArticleCategory category : articleList) {
            if (category.getParent_id() == parentId) {
                childList.add(category);
            }
        }
        for (ArticleCategory cate : childList) {
            cate.setSubCategory(_getChild(cate.getId(), articleList));
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
